package org.HisCanvas.ChrisRiffle.JFlightLog.swingUi.recordDetailWindow;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JOptionPane;

import org.HisCanvas.ChrisRiffle.JFlightLog.dataModel.LogBookRec;
import org.HisCanvas.ChrisRiffle.JFlightLog.launching.JFlightLogController;
import org.HisCanvas.ChrisRiffle.JFlightLog.logging.LogController;
import org.HisCanvas.ChrisRiffle.JFlightLog.swingUi.mainTopFrame.FlightLogMainFrameController;
import org.HisCanvas.ChrisRiffle.JFlightLog.swingUi.recordDetailWindow.LogBookRecDialogController.WINDOW_MODE;
import org.HisCanvas.ChrisRiffle.JFlightLog.swingUi.table.FlightLogTableController;




public class RecDetailOkCancelButtonPanelListener implements ActionListener{
	
	
	public static final String OK_BUTTON_CLICK = "OK_BUTTON_CLICK";
	
	public static final String CANCEL_BUTTON_CLICK = "CANCEL_BUTTON_CLICK";
		
	private LogBookRecDialogController parentDialogController;
	
	
	
	public RecDetailOkCancelButtonPanelListener(LogBookRecDialogController pParentDialogController) {
		
		this.parentDialogController = pParentDialogController;
	}
	
	
	
	@Override
	public void actionPerformed(ActionEvent e) {

		String userCommand = e.getActionCommand();
		
		if(OK_BUTTON_CLICK.equals(userCommand)){
			
			handleOkButtonClick();
			
			
		}else if(CANCEL_BUTTON_CLICK.equals(userCommand)){
			
			handleCancelButtonClick();
			
		}
		
	}




	private void handleCancelButtonClick() {
		
		parentDialogController.setOkButtonClicked(false);
				
		parentDialogController.getLogBookRecDialog().dispose();
		
	}




	private void handleOkButtonClick() {
				
						
		parentDialogController.setOkButtonClicked(true);
		
		LogBookRec rec = parentDialogController.updateCurrentFlightRecWithDataFromWindow();
								
		try {
			
			WINDOW_MODE windowMode = parentDialogController.getCurrentWindowMode();
			
			if(WINDOW_MODE.ADD.equals(windowMode)){
				
				JFlightLogController.instance().getLogBookDao().addLogBookRec(rec);
				
			}else if(WINDOW_MODE.EDIT.equals(windowMode)){
				
				JFlightLogController.instance().getLogBookDao().modifyLogBookRec(rec);
			}
									
			//refresh the table gui view so the user can see the changes
			FlightLogTableController.instance().refreshTableView();						

		} catch (Exception e) {

			LogController.severe("Could not save log book record");
			e.printStackTrace();
		}
				
		parentDialogController.getLogBookRecDialog().dispose();
		
	}

}




